#include "app_mqtt.h"
#include "MQTTClient.h"
#include "log.h"
#include "string.h"

MQTTClient client;
static MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
static MQTTClient_message pubmsg = MQTTClient_message_initializer; // MQTT客户端要发布的消息

int (*app_mqtt_recieve_callback)(char *);

static void app_mqtt_connerctionLost(void *context, char *cause)
{
    log_error("Connection lost: %s", cause);
}

/**
 * @brief 消息到达回调函数
 */
int app_mqtt_messageArrived(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    // 1.把消息内容取出来，用内部的回调函数调用
    if (app_mqtt_recieve_callback == NULL)
    {
        log_error("app_mqtt_recieve_callback is NULL");
        return 0;
    }

    int ret = app_mqtt_recieve_callback((char *)message->payload);
    if (ret == 0)
    {
        return 1;
    }
    else
    {
        log_error("app_mqtt_recieve_callback failed");
        return 0;
    }
}

/**
 * @brief mqtt消息发送成功回调函数
 * 只有在QoS>0的情况下才会调用
 */
void app_mqtt_deliveryComplete(void *context, MQTTClient_deliveryToken dt)
{
    log_debug("Message delivery complete");
}
int app_mqtt_init(void)
{
    int result = MQTTClient_create(&client, MQTT_BROKER_URL, MQTT_CLIENT_ID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
    if (result == -1)
    {
        log_error("Failed to create MQTT client, error code");
    }
    // 2.设置回调函数
    MQTTClient_setCallbacks(client, NULL, app_mqtt_connerctionLost, app_mqtt_messageArrived, app_mqtt_deliveryComplete);
    // 3.连接MQTT服务器
    result = MQTTClient_connect(client, &conn_opts);
    if (result == -1)
    {
        perror("Failed to connect to MQTT server");
        return -1;
    }
    // 4.订阅主题
    result = MQTTClient_subscribe(client, MQTT_SUBSCRIBE_TOPIC, MQTT_PUBLISH_QOS);
    if (result == -1)
    {
        log_error("MQTTClient_subscribe failed");
        return -1;
    }
    return 0;
}

/**
 * @brief 发送MQTT消息
 *
 */
int app_mqtt_publish(char *payload)
{
    pubmsg.payload = payload;
    pubmsg.payloadlen = strlen(payload);
    MQTTClient_publishMessage(client, MQTT_PUBLISH_TOPIC, &pubmsg, NULL);
    return 0;
}

/**
 * @brief MQTT消息接收回调函数
 *
 */
int app_mqtt_recv_callback(int (*callback)(char *))
{
    app_mqtt_recieve_callback = callback;
    return 0;
}

/**
 * @brief 销毁MQTT
 *
 */
void app_mqtt_destroy(void)
{
    MQTTClient_disconnect(client, 10000);
    MQTTClient_destroy(&client);
}
